package com.liaoyin.travel.service.approval;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.business.util.AttendanceUtil;
import com.liaoyin.travel.view.moble.approval.PacketRecordDetailsView;
import com.liaoyin.travel.view.user.UserView;
import com.liaoyin.travel.vo.approval.ApprovalPacketRecordVo;
import com.liaoyin.travel.vo.approval.InsertOrUpdateApprovalRecordVo;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.approval.AskForLeavePacketRecordMapper;
import com.liaoyin.travel.entity.approval.AskForLeavePacketApplicant;
import com.liaoyin.travel.entity.approval.AskForLeavePacketRecord;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.SnowIdUtil;
import com.liaoyin.travel.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 请假申请-审批分组-请求人
 *
 * @author kuang.jiazhuo
 * @date 2019-11-21 17:58
 */
@Service
public class AskForLeavePacketRecordService extends BaseService<AskForLeavePacketRecordMapper, AskForLeavePacketRecord> {

    @Resource
    AskForLeavePacketApplicantService askForLeavePacketApplicantService;

    @Resource
    UsersService usersService;

    /**
     * @方法名：insertOrUpdateAskForLeavePacketRecord
     * @描述： 新增或修改请假申请的审批分组
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/21 18:03
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateAskForLeavePacketRecord(InsertOrUpdateApprovalRecordVo askForLeavePacketRecordVo) {
        //获取到用户的登录信息,判断用户是否登录
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        /** 景区id */
        String scenicId = user.getScenicId();

        int result = 0;
        //补卡申请表的id
        String id = askForLeavePacketRecordVo.getPacketId();
        System.err.println("id="+id);
        //申请人id字符串集
        String applicantIds = askForLeavePacketRecordVo.getApplicantIdS();
        String[] applicantIdArray = applicantIds.split(",");
        List<String> applicantIdList = Arrays.asList(applicantIdArray);
        //审批人id
        String approvedBy = askForLeavePacketRecordVo.getApprovedBy();
        //为了防止前端传入的审批人最后一位有,要执行一次去掉最后一个字符操作
        approvedBy = approvedBy.substring(0, approvedBy.length()-1);
        /** 审批人只能选择管理员*/
        if(AttendanceUtil.isNotAdministrators(approvedBy)){
            throw new BusinessException("management.is.approvedBy");
        }
        //分组名称
        String packetName = askForLeavePacketRecordVo.getPacketName().trim();

        //是否删除
        String isDelete = askForLeavePacketRecordVo.getIsDelete();
        AskForLeavePacketRecord askForLeavePacketRecord = new AskForLeavePacketRecord();
        if(id==null || id.equals("")){
            //判断分组名字是否重复
            judgePacketNameRepetition(packetName,null);
            /** 新增*/
            String packetId = SnowIdUtil.getInstance().nextId();
            askForLeavePacketRecord
                    .setId(packetId)
                    .setCreateBy(user.getId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setPacketName(packetName)
                    .setApprovedBy(approvedBy)
                    .setScenicId(scenicId);
            result = this.mapper.insert(askForLeavePacketRecord);
            if(result>0){
                this.askForLeavePacketApplicantService.insertOrUpdateApplicant(applicantIdList,packetId,1);
            }
        }else{
            //判断分组名字是否重复
            judgePacketNameRepetition(packetName,id);
            /** 更新*/
            //如果删除
            if(StringUtil.isNotBlank(isDelete) && VariableConstants.STRING_CONSTANT_1.equals(isDelete)){
                result = this.deleteAskForLeavePacketRecord(id);
            }else{
                //不是删除
                askForLeavePacketRecord
                        .setId(id)
                        .setUpdateBy(user.getId())
                        .setUpdateTime(LocalDateTime.now())
                        .setPacketName(packetName)
                        .setApprovedBy(approvedBy);
                System.err.println("approvedBy="+approvedBy);
                result = this.mapper.updateById(askForLeavePacketRecord);
                if(result>0){
                    this.askForLeavePacketApplicantService.insertOrUpdateApplicant(applicantIdList,id,2);
                }
            }

        }
        return result;
    }

    /**
     * @方法名：judgePacketNameRepetition
     * @描述： 判断分组名是否重复,若重复抛出异常
     * @作者： kjz
     * @日期： Created in 2020/4/14 14:10
     */
    public void judgePacketNameRepetition(String packetName, String id) {
        int count = mapper.selectRecordCountByPacketName(packetName,id);
        if(count>0){
            throw new BusinessException("packetName.is.exist");
        }
    }

    /**
     * @方法名：deleteAskForLeavePacketRecord
     * @描述： 物理删除请假申请审批分组
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/21 18:58
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteAskForLeavePacketRecord(String id) {
        Example example = new Example(AskForLeavePacketRecord.class);
        example.and().andEqualTo("id", id);
        int result = this.mapper.deleteByPrimaryKey(example);
        if(result>0){
            this.askForLeavePacketApplicantService.deleteAskForLeavePacketApplicantByPacketId(id);
        }
        return result;
    }

    /**
     * @方法名：selectAskForLeavePacketRecordByCondition
     * @描述： 后台-按条件查完【请假】审批分组列表(带分页)
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/21 21:08
     */
    public PageInfo<AskForLeavePacketRecord> selectAskForLeavePacketRecordByCondition(ApprovalPacketRecordVo approvalPacketRecordVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        approvalPacketRecordVo.setScenicId(scenicId);

        PageHelper.startPage(approvalPacketRecordVo.getNum(),approvalPacketRecordVo.getSize());
        List<AskForLeavePacketRecord> list = this.mapper.selectAskForLeavePacketRecordByCondition(approvalPacketRecordVo);
        PageInfo<AskForLeavePacketRecord> p = new PageInfo<>(list);
        return p;
    }

    /**
     * @方法名：deleteAskForLeavePacketRecordByIds
     * @描述： 批量删除补卡审批分组
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/25 15:50
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteAskForLeavePacketRecordByIds(String ids) {
        String[] id = ids.split(",");
        List<String> list = Arrays.asList(id);
        int result = 0;
        for(String packId:list){
            result += this.mapper.deleteAskForLeavePacketRecordById(packId);
            this.askForLeavePacketApplicantService.deleteAskForLeavePacketApplicantByPacketId(packId);
        }
        return result;
    }

    /**
     * @方法名：selectAskForLeavePacketDetailsById
     * @描述： 根据id查询请假审批分组的详情
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/25 19:21
     */
    public PacketRecordDetailsView selectAskForLeavePacketDetailsById(String id) {
        AskForLeavePacketRecord askForLeavePacketRecord = this.mapper.selectAskForLeavePacketById(id);
        List<AskForLeavePacketApplicant> applicants = this.askForLeavePacketApplicantService.selectApplicantByPacketId(id);
        PacketRecordDetailsView packetRecordDetailsView = new PacketRecordDetailsView();
        List<UserView> applicantList = new ArrayList<>();
        for(AskForLeavePacketApplicant applicant:applicants){
            if(StringUtil.isNotEmpty(applicant.getApplicantId())){
                UserView userView = usersService.selectUserViewById(applicant.getApplicantId());
                applicantList.add(userView);
            }
        }
        UserView approver = usersService.selectUserViewById(askForLeavePacketRecord.getApprovedBy());
        packetRecordDetailsView.setApprover(approver)
                .setApplicantList(applicantList)
                .setCreateTime(askForLeavePacketRecord.getCreateTime())
                .setPacketName(askForLeavePacketRecord.getPacketName());
        return packetRecordDetailsView;
    }
}
